package com.automation.utils;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;

public class AppiumTest {

    // 使用正确的 Appium 2.0 端点
    private static final String APPIUM_SERVER_URL = "http://127.0.0.1:4723/wd/hub";

    public static void main(String[] args) {

        //执行代码前，先启动
        // 1、adb devices
        // 2、adb connect 127.0.0.1:5555
        // 3、adb start-server
        AndroidDriver driver = init();
        

    }

    public static AndroidDriver init(){
        try {
            // 1. 创建选项对象
            UiAutomator2Options options = new UiAutomator2Options();

            // 2. 设置基础能力
            options.setPlatformName("Android");
            options.setPlatformVersion("7.1.2");
            options.setUdid("127.0.0.1:5555"); // 关键：只设置udid
            options.setAutomationName("UiAutomator2");

            // 3. 应用配置
//            options.setAppPackage("com.netease.cloudmusic");
            options.setAppActivity(".activity.MainActivity");

            // 4. 键盘和权限设置
//            options.setUnicodeKeyboard(true);
//            options.setResetKeyboard(true);
            options.setAutoGrantPermissions(true);

            // 5. 会话设置
            options.setNoReset(true);
            options.setNewCommandTimeout(Duration.ofSeconds(3600));
            options.setEnsureWebviewsHavePages(true);
            options.setNativeWebScreenshot(true);
//            options.setConnectHardwareKeyboard(true);

            // 6. 雷电模拟器专用优化
            options.setCapability("systemPort", 8200);
            options.setCapability("skipDeviceInitialization", true);
            options.setCapability("skipServerInstallation", true);
            options.setCapability("disableAndroidWatchers", true);

            // 7. 移除冲突的deviceName
            // 不要设置deviceName，它会导致冲突

            // 8. 创建驱动实例（使用新端点）
            AndroidDriver driver = new AndroidDriver(new URL(APPIUM_SERVER_URL), options);

            // 9. 设置隐式等待

            // 10. 验证连接
            System.out.println("设备状态: " + driver.getStatus());
            System.out.println("当前Activity: " + driver.currentActivity());
            return driver;
        } catch (MalformedURLException e) {
            System.err.println("URL格式错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("连接失败: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

}